#include "soundserver.h"
#include <QTextCodec>

SoundServer::SoundServer(QObject *parent) :
    QObject(parent)
{
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    inputDevs =  QAudioDeviceInfo::availableDevices(QAudio::AudioInput);

    tcpServer = NULL;
    tcpSocket = NULL;

    tcpServer = new QTcpServer(this);
    tcpServer->listen(QHostAddress::Any,TCPPORT);

    connect(tcpServer,&QTcpServer::newConnection,[=](){
        //取出建立好连接的的套接字
        tcpSocket = tcpServer->nextPendingConnection();

        //获取对方的IP和端口
        clientIP = tcpSocket->peerAddress().toString();

        connect(tcpSocket, &QTcpSocket::readyRead,[=](){
             QByteArray buf = tcpSocket->readAll();
             recvMess(buf.data());
         });

    });
}

SoundServer::~SoundServer()
{
    delete tcpServer;
}

void SoundServer::recvMess(char data[])
{
    if(cmp_str(data,"Device"))
    {
        for(int i=0;i<inputDevs.size();i++)
        {
            QByteArray temp=inputDevs.at(i).deviceName().toLocal8Bit();
            temp.prepend("ID:");
            sendMess(temp);
        }
    }
    else if(cmp_str(data,"Rec_"))
    {
        int index=0;
        sscanf(&data[4],"%d",&index);
        inputDevInfo=inputDevs.at(index);

        int quality=0;
        sscanf(&data[6],"%d",&quality);

        int delay=0;
        sscanf(&data[8],"%d",&delay);

        serverSend.init(clientIP, SERVER_SEND_PORT, CLIENT_RECV_PORT, quality,inputDevInfo);
        serverSend.mystart(delay);
    }
    else if(cmp_str(data,"StopRec"))
    {
        qDebug() <<"StopRec"<<endl;
        serverSend.mystop();
    }
    else if(cmp_str(data,"Play_"))
    {
        int quality=0;
        sscanf(&data[5],"%d",&quality);
        serverRecv.init(quality,SERVER_RECV_PORT);
        serverRecv.start();
        qDebug() <<"Play_quality:"<<quality<<endl;
    }
    else if(cmp_str(data,"StopPlay"))
    {
        serverRecv.stop();
        qDebug() <<"StopPlay"<<endl;
    }
}


void SoundServer::sendMess(QByteArray data)
{
    QByteArray m=data.append("#*#",3);
    int len=tcpSocket->write(m);
}

